<template>
  <view class="page">
    <!-- 主容器使用flex布局 -->
    <view class="container">
      <!-- 可滚动内容区域 -->
      <scroll-view scroll-y class="scroll-view" enable-back-to-top>
        <view class="cart-header">
          <text class="clear-cart" @click="clearCart">清空购物车</text>
        </view>

        <!-- 按店铺分组显示商品 -->
        <view class="store-list">
          <view v-for="(store) in groupedCartItems" :key="store.storeId" class="store-item">
            <!-- 店铺信息 -->
            <view class="store-header">
              <view class="store-select">
                <checkbox :checked="store.isSelected" @click="toggleStoreSelect(store)" />
                <text class="select-text">全选</text>
              </view>
              <text class="store-name">{{store.storeName}}</text>
            </view>

            <!-- 店铺商品列表 -->
            <view class="goods-list">
              <view v-for="(item, index) in store.goods" :key="index" class="goods-item">
                <view class="item-left">
                  <checkbox :checked="item.isSelected" @click="toggleSelect(item, store)" />
                  <image :src="`/static/${item.imgUrl}`" class="goods-image"></image>
                </view>

                <view class="item-right">
                  <view class="goods-info">
                    <text class="goods-name">{{item.name}}</text>
                    <text class="goods-sales">月售{{item.sales}}件</text>
                    <view class="price-box">
                      <text class="current-price">¥{{item.price}}</text>
                      <text class="original-price" v-if="item.oldPrice">¥{{item.oldPrice}}</text>
                    </view>
                  </view>

                  <view class="stepper">
                    <text class="btn minus" @click="decreaseQuantity(item)">-</text>
                    <text class="number">{{item.quantity}}</text>
                    <text class="btn plus" @click="increaseQuantity(item)">+</text>
                  </view>
                </view>
              </view>
            </view>

            <!-- 每个店铺的结算栏 -->
            <view class="store-footer" v-if="store.goods.length > 0">
              <view class="footer-left">
                <text class="total-text">合计：</text>
                <text class="total-price">¥{{getStoreTotal(store).toFixed(2)}}</text>
              </view>
              <button class="submit-btn" @click="handleStoreCheckout(store)">
                去结算({{getStoreSelectedCount(store)}})
              </button>
            </view>
          </view>
        </view>

        <!-- 空购物车提示 -->
        <view v-if="totalCount === 0" class="empty-cart">
          <image src="/static/images/empty-cart.png" class="empty-img"></image>
          <text class="empty-text">购物车空空如也</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      groupedCartItems: [],
    };
  },

  computed: {
    totalCount() {
      return this.groupedCartItems.reduce((total, store) =>
        total + store.goods.length, 0);
    },

    selectedCount() {
      return this.groupedCartItems.reduce((total, store) =>
        total + store.goods.filter(item => item.isSelected).length, 0);
    },

    totalPrice() {
      return this.groupedCartItems.reduce((total, store) => {
        return total + store.goods
          .filter(item => item.isSelected)
          .reduce((sum, item) => sum + (item.price * item.quantity), 0);
      }, 0);
    }
  },

  onShow() {
    this.loadCartItems();
  },

  methods: {
    loadCartItems() {
      const items = uni.getStorageSync('cartItems') || [];

      const groupedItems = {};
      items.forEach(item => {
        if (!groupedItems[item.storeId]) {
          groupedItems[item.storeId] = {
            storeId: item.storeId,
            storeName: item.storeName,
            isSelected: false,
            goods: []
          };
        }
        groupedItems[item.storeId].goods.push({
          ...item,
          isSelected: item.isSelected || false
        });
      });

      this.groupedCartItems = Object.values(groupedItems);
    },

    toggleSelect(item, store) {
      item.isSelected = !item.isSelected;
      store.isSelected = store.goods.every(item => item.isSelected);
      this.updateCart();
    },

    toggleStoreSelect(store) {
      store.isSelected = !store.isSelected;
      store.goods.forEach(item => {
        item.isSelected = store.isSelected;
      });
      this.updateCart();
    },

    updateCart() {
      const flatItems = this.groupedCartItems.reduce((items, store) => {
        return items.concat(store.goods);
      }, []);
      uni.setStorageSync('cartItems', flatItems);
    },

    increaseQuantity(item) {
      item.quantity++;
      this.updateCart();
    },

    decreaseQuantity(item) {
      if (item.quantity > 1) {
        item.quantity--;
      } else {
        this.removeItem(item);
      }
      this.updateCart();
    },

    removeItem(item) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: (res) => {
          if (res.confirm) {
            const index = this.groupedCartItems.findIndex(store =>
              store.goods.some(i => i._id === item._id));
            if (index !== -1) {
              const store = this.groupedCartItems[index];
              const goodsIndex = store.goods.findIndex(i => i._id === item._id);
              if (goodsIndex !== -1) {
                store.goods.splice(goodsIndex, 1);
              }
              this.updateCart();
            }
          }
        }
      });
    },

    clearCart() {
      if (this.totalCount === 0) return;

      uni.showModal({
        title: '提示',
        content: '确定要清空购物车吗？',
        success: (res) => {
          if (res.confirm) {
            this.groupedCartItems = [];
            uni.removeStorageSync('cartItems');
          }
        }
      });
    },

    getStoreSelectedCount(store) {
      return store.goods.filter(item => item.isSelected).length;
    },

    getStoreTotal(store) {
      return store.goods
        .filter(item => item.isSelected)
        .reduce((total, item) => total + (item.price * item.quantity), 0);
    },

    handleStoreCheckout(store) {
      const selectedCount = this.getStoreSelectedCount(store);
      if (selectedCount === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }

      const selectedItems = store.goods.filter(item => item.isSelected);
      uni.setStorageSync('selectedCartItems', selectedItems);

      uni.navigateTo({
        url: '/pages/must/must'
      });
    },
  }
};
</script>

<style scoped>
/* 基础样式 */
page {
  height: 100%;
  background-color: #f8f9fa;
}

.page {
  height: 100%;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.scroll-view {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  padding: 16px;
}

/* 头部样式 */
.cart-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 16px;
  background-color: #ffffff;
  border-bottom: 1px solid #e9ecef;
  font-size: 14px;
  color: #6c757d;
}

.clear-cart {
  cursor: pointer;
}

/* 商品列表样式 */
.goods-list {
  padding-bottom: 16px;
}

.goods-item {
  display: flex;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #ffffff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  transition: box-shadow 0.3s ease;
}

.goods-item:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
}

.item-left {
  display: flex;
  align-items: center;
  margin-right: 16px;
}

.goods-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.item-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 16px;
  font-weight: 600;
  color: #343a40;
  margin-bottom: 4px;
}

.goods-sales {
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 8px;
}

.price-box {
  display: flex;
  align-items: center;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #dc3545;
}

.original-price {
  font-size: 12px;
  color: #6c757d;
  text-decoration: line-through;
  margin-left: 8px;
}

/* 数量加减器 */
.stepper {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.btn {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.minus {
  background-color: #e9ecef;
  color: #6c757d;
}

.minus:hover {
  background-color: #dee2e6;
}

.plus {
  background-color: #007bff;
  color: #ffffff;
}

.plus:hover {
  background-color: #0069d9;
}

.number {
  margin: 0 12px;
  font-size: 16px;
  min-width: 20px;
  text-align: center;
}

/* 空购物车样式 */
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 64px;
}

.empty-img {
  width: 120px;
  height: 120px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: #6c757d;
  margin-bottom: 32px;
}

/* 店铺相关样式 */
.store-list {
  margin-bottom: 16px;
}

.store-item {
  margin-bottom: 16px;
  background-color: #ffffff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
}

.store-header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
}

.store-select {
  display: flex;
  align-items: center;
}

.select-text {
  font-size: 14px;
  color: #343a40;
  margin-left: 8px;
}

.store-name {
  font-size: 16px;
  font-weight: 600;
  color: #343a40;
  margin-left: 16px;
}

/* 店铺结算栏样式 */
.store-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #ffffff;
  border-top: 1px solid #e9ecef;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
}

.total-text {
  font-size: 14px;
  color: #343a40;
}

.total-price {
  font-size: 16px;
  font-weight: 600;
  color: #dc3545;
  margin-left: 8px;
}

.submit-btn {
  padding: 8px 16px;
  background-color: #007bff;
  color: #ffffff;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.submit-btn:hover {
  background-color: #0069d9;
}
</style>    